import asyncio
import logging
from typing import List, Dict, Tuple
from datetime import datetime

logger = logging.getLogger(__name__)


class AIChatService:
    """AI对话服务"""

    def __init__(self, chat_history_limit: int = 10):
        self.chat_history_limit = chat_history_limit

    async def process_chat_message(self, device_id: str, user_message: str, chat_history: List[Dict]) -> Tuple[
        str, List[Dict]]:
        """处理AI对话消息"""
        try:
            # 添加用户消息到历史
            updated_history = chat_history.copy()
            updated_history.append({
                "role": "user",
                "content": user_message,
                "timestamp": datetime.now().isoformat()
            })

            # 调用AI服务生成回复
            ai_response = await self.generate_ai_response(user_message, updated_history)

            # 添加AI回复到历史
            updated_history.append({
                "role": "assistant",
                "content": ai_response,
                "timestamp": datetime.now().isoformat()
            })

            # 限制历史记录长度
            if len(updated_history) > self.chat_history_limit:
                updated_history = updated_history[-self.chat_history_limit:]

            return ai_response, updated_history

        except Exception as e:
            logger.error(f"AI对话处理失败: {str(e)}")
            return "抱歉，我现在无法处理您的请求，请稍后再试。", chat_history

    async def generate_ai_response(self, user_message: str, history: List[Dict]) -> str:
        """生成AI回复（这里使用模拟实现，可以替换为真实的AI服务）"""
        # 模拟AI处理时间
        await asyncio.sleep(0.5)

        # 简单的规则回复（实际应用中可替换为 OpenAI、文心一言等AI服务）
        user_message_lower = user_message.lower()

        if any(word in user_message_lower for word in ["你好", "hello", "hi"]):
            return "你好！我是AI助手，很高兴为您服务。"
        elif any(word in user_message_lower for word in ["天气", "weather"]):
            return "我是一个AI助手，无法获取实时天气信息。建议您查看天气预报应用。"
        elif any(word in user_message_lower for word in ["设备", "device"]):
            return "关于设备管理的问题，我可以帮您解答基本操作和状态查询。"
        elif any(word in user_message_lower for word in ["帮助", "help"]):
            return """我可以帮助您处理以下事务：
                1. 设备状态查询
                2. 数据报告分析
                3. 一般问题解答
                4. 技术支持
                
                请告诉我您需要什么帮助？"""
        else:
            return f"我已经收到您的消息：\"{user_message}\"。这是一个模拟的AI回复，在实际应用中会连接真实的AI服务。"